<template>
  <div>
    <el-tree
      ref="tree"
      :data="treeData"
      :props="defaultProps"
      :auto-expand-parent="true"
      :default-expanded-keys="keys"
      :default-expand-all="true"
      node-key="id"
      :highlight-current="true"
      :expand-on-click-node="false"
      @node-click="handleNodeClick"
    />
  </div>
</template>

<script>
export default {
  name: 'Tree',
  props: {
    selectedNodeId: {
      type: String,
      default: ''
    },
    keys: []
  },
  data() {
    return {
      treeData: [
        {
          id: '1',
          label: '一级节点1',
          children: [
            {
              id: '1-1',
              label: '二级节点1-1',
              children: [
                { id: '1-1-1', label: '三级节点1-1-1' },
                { id: '1-1-2', label: '三级节点1-1-2' }
              ]
            },
            {
              id: '1-2',
              label: '二级节点1-2',
              children: [
                { id: '1-2-1', label: '三级节点1-2-1' },
                { id: '1-2-2', label: '三级节点1-2-2' }
              ]
            }
          ]
        },
        {
          id: '2',
          label: '一级节点2',
          children: [
            {
              id: '2-1',
              label: '二级节点2-1',
              children: [
                { id: '2-1-1', label: '三级节点2-1-1' },
                { id: '2-1-2', label: '三级节点2-1-2' }
              ]
            }
          ]
        }
      ],
      defaultProps: {
        children: 'children',
        label: 'label',
        value: 'id'
      }
    }
  },
  mounted() {
    if (this.selectedNodeId) {
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.selectedNodeId)
      })
    }
  },
  methods: {
    handleNodeClick(data) {
      console.log('选中节点ID:', data.id)
      // 这里可以发射一个事件，让父组件知道哪个节点被选中了
      this.$emit('node-click', data.id)
    },
    expandAndSelectNodeId(id) {
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(id)
        // 确保当前节点被高亮d
      })
    }
  }
}
</script>
